package io.renren.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * 文件上传<br>
 * 本地上传、阿里云OSS上传
 * 
 * @author ypj
 *
 */
public class UploadUtil {
    private static Logger logger = LoggerFactory.getLogger(UploadUtil.class);
    //本地上传路径
    private static String savePath = "";

    /**
     * 允许上传的文件格式
     *
     * @return
     */
    public static Map<String, String> getAllowUploadExt() {
        Map<String, String> extMap = new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
        return extMap;
    }

    /**
     * 阿里云OSS上传
     *
     * @param imgFile
     * @param dir
     * @param subDir
     * @return
     */
    public static JSONObject uploadOSS(MultipartFile imgFile, String dir, String subDir) {
        try {
            String fileName = imgFile.getOriginalFilename();
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            Map<String, String> allowExt = getAllowUploadExt();
            // 检查目录
            if (!allowExt.containsKey(dir)) {
                return uploadReturn(false, "目录名不正确");
            }
            // 检查扩展名
            if (!Arrays.<String>asList(allowExt.get(dir).split(",")).contains(fileExt)) {
                return uploadReturn(false, "文件格式错误");
            }
            // 设置保存路径
            String relativePath = dir + "/";
            if (StringUtils.isNotBlank(subDir)) {
                relativePath += subDir + "/";
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
            String ym = sdf.format(new Date());
            relativePath += ym + "/";
            // 重新命名
            String newFileName = String.valueOf(System.currentTimeMillis());
            newFileName = newFileName + "." + fileExt;
            InputStream inputStream = imgFile.getInputStream();
            Long length = imgFile.getSize();
            OSSUtil.uploadFile(relativePath + newFileName, inputStream, length);
            return uploadReturn(true, relativePath + newFileName);
        } catch (Exception e) {
            logger.error("上传文件异常：" + e.getMessage());
            return uploadReturn(false, "上传失败");
        }
    }

    /**
     * 本地上传
     *
     * @param imgFile
     * @param dir
     * @param subDir
     * @return
     */
    public static JSONObject uploadLocal(MultipartFile imgFile, String dir, String subDir) {
        try {
            String fileName = imgFile.getOriginalFilename();
            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            Map<String, String> allowExt = getAllowUploadExt();
            // 检查目录
            if (!allowExt.containsKey(dir)) {
                return uploadReturn(false, "目录名不正确");
            }
            // 检查扩展名
            if (!Arrays.<String>asList(allowExt.get(dir).split(",")).contains(fileExt)) {
                return uploadReturn(false, "文件格式错误");
            }
            // 设置保存路径
            String relativePath = dir + "/";
            if (StringUtils.isNotBlank(subDir)) {
                relativePath += subDir + "/";
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
            String ym = sdf.format(new Date());
            relativePath += ym + "/";
            // 文件保存目录路径
            //String savePath = CacheManager.getProperty("file.upload.path");
            savePath += relativePath;
            // 创建文件夹
            File dirFile = new File(savePath);
            if (!dirFile.exists()) {
                dirFile.mkdirs();
            }
            // 重新命名
            String newFileName = String.valueOf(System.currentTimeMillis());
            String newFileName1 = newFileName + "_1." + fileExt;// 小图
            String newFileName2 = newFileName + "_2." + fileExt;// 中图
            newFileName += newFileName + "." + fileExt;// 大图 ，也是原图
            File uploadedFile1 = new File(savePath, newFileName1);
            File uploadedFile2 = new File(savePath, newFileName2);
            File uploadedFile = new File(savePath, newFileName);
            imgFile.transferTo(uploadedFile);
            //ImageUtils.ratioZoom2(uploadedFile, uploadedFile1,Double.valueOf(200));
            //ImageUtils.ratioZoom2(uploadedFile, uploadedFile2, Double.valueOf(350));
            return uploadReturn(true, relativePath + newFileName);
        } catch (Exception e) {
            logger.error("上传文件异常：" + e.getMessage());
            return uploadReturn(false, "上传失败");
        }
    }

    /**
     * 上传返回结果
     * @param bo      true：成功，false：失败
     * @param message bo=true:文件相对路径/bo=false:错误信息
     * @return
     */
    public static JSONObject uploadReturn(boolean bo, String message) {
        JSONObject obj = new JSONObject();
        if (bo) {
            obj.put("success", message);
        } else {
            obj.put("error", message);
        }
        return obj;
    }
}
